package controller

import (
	"github.com/gin-gonic/gin"
	"go-proxy/admin/dto"
	"go-proxy/admin/vo"
	"go-proxy/common"
	"go-proxy/config"
	"go-proxy/util"
)

func Login(c *gin.Context) {
	var param dto.LoginDTO
	err := c.ShouldBindJSON(&param)
	if err != nil {
		vo.BizError(c, err.Error())
		return
	}

	adminConfig := config.Config.Admin
	if len(adminConfig.Username) <= 0 || len(adminConfig.Password) <= 0 || len(adminConfig.Secret) <= 0 {
		vo.BizError(c, "登录鉴权帐号信息未配置，请联系管理员")
		return
	}

	if adminConfig.Username != param.Username || adminConfig.Password != param.Password {
		vo.Fail(c, vo.ErrLoginFail)
		return
	}

	// 生成jwt token
	if adminConfig.TokenExpire <= 0 {
		adminConfig.TokenExpire = 1296000
	}

	token, err := util.CreatToken(adminConfig.Username, adminConfig.TokenExpire, adminConfig.Secret)
	if err != nil {
		vo.Fail(c, vo.ErrCreateToken)
		return
	}

	vo.OKData(c, token)
}

func GetUserInfo(c *gin.Context) {
	username, ok := c.Get(common.USERNAME)
	if !ok {
		vo.BizError(c, "获取用户信息失败")
		return
	}

	userInfo := vo.UserInfoVO{
		Username: username.(string),
		Roles:    []string{"all"},
	}
	vo.OKData(c, userInfo)
}
